<template>
  <div>
    <!-- 菜单树 -->
    <el-tree
      ref="tree"
      :data="treeData"
      show-checkbox
      node-key="id"
      :default-checked-keys="checked"
      :default-expand-all="true"
      :props="defaultProps"
    >
    </el-tree>
    <!-- 按钮组 -->
    <div class="btns">
      <el-button type="primary" @click="submitData">确定</el-button>
    </div>
  </div>
</template>

<script>
import {
  getAccesses,
  addRoleAccess,
  getAccessesByRole,
} from "../../../../api/access";
export default {
  props: ["roleId"],
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      checked: [],
    };
  },
  mounted() {
    this.getCheckedData()
    getAccesses().then((res) => {
      if (res.success){
       
        this.treeData = res.data;
        console.log(this.treeData)
        
      } 
    });
  },
  methods: {
    getCheckedData() {
      getAccessesByRole(this.roleId).then((res) => {
        if (res.success) {
          res.data.map((item, index) => {
            this.checked.push(item.id);
          });
          console.log(this.checked)
        }
      });
    },
    //
    submitData() {
      console.log(this.roleId, this.getTreeCheckedId());
      addRoleAccess({
        id: this.roleId,
        accessIds: this.getTreeCheckedId(),
      }).then((res) => {
        console.log(res);
        if (res.success) this.$emit("close");
      });
    },
    getTreeCheckedId() {
      let res = this.$refs.tree.getCheckedNodes();
      let arr = [];
      res.forEach((item) => {
        arr.push(item.id);
      });
      return arr;
    },
  },
};
</script>

<style scoped>
.btns {
  margin-top: 20px;
  text-align: center;
}
</style>